import { vh, vw } from "@/common/dimensions";
import globalStyles from "@/common/styles/globalStyles";
import LazyImage from "@/components/LazyImage";
import SideMenuWithModal from "@/components/SideMenuWithModal";
import { ALI_OSS_PATH } from "@/config/path";
import { resultListServer } from "@/servers/app-servers";
import {
	currentWorkListAtom,
	pageParamsAtom,
	PageParamsType,
	ResultItemType,
	shouldFetchResultsAtom,
	WorkItemType,
	workListAtom,
} from "@/store/work";
import { LinearGradient } from "expo-linear-gradient";
import { useAtom } from "jotai";
import React, { useEffect, useRef, useState } from "react";
import { ActivityIndicator, Button, findNodeHandle, Image, Pressable, StyleSheet, Text, TouchableOpacity, View } from "react-native";
import WorkUse, { CurrentPropsType } from "./WorkUse";
import dayjs from "dayjs";
import { router } from "expo-router";
import TransitionLoading from "@/components/TransitionLoading";
import { resultShowAtom } from "@/store/home";
import { userInfoAtom } from "@/store/user";

export default function WorkList(props:{pageParams:PageParamsType , nextPage:boolean , changeNextPage:Function}) {
    let {pageParams , nextPage , changeNextPage } = props
	// 用户信息
	const [ userInfo ] = useAtom(userInfoAtom)
	// 作品列表
	const [workList, setWorkList] = useAtom<WorkItemType[]>(workListAtom);
    // 页面初始化时的 loading 状态
    const [loading, setLoading] = useState<boolean>(true); 
	// 标记当前结果页是否为空
	const [currentWorkList, setCurrentWorkList] = useAtom<boolean>(currentWorkListAtom);
	// 当前账号是否有作品
	const [hasWork, setHasWork] = useState<boolean>(true);
    // 侧边栏是否显示
    const [sideModalShow ,setSideModalShow] = useState<boolean>(false)
    // 这个ref用来引用触发 `openMenu` 的按钮
	const triggerButtonRefs = useRef<{ [key: string]: View | null }>({});
    // 屏幕到触发侧边栏元素的距离
	const [scrollHeight, setScrollHeight] = useState(0);
    // 触发侧边栏元素的高度
    const [sideViewHeight , setSideViewHeight] = useState(0);
    // 侧边栏弹出方向
    const [sideType , setSideType ] = useState('')
    // 管理长按状态的 state，用 r.path 作为 key
    const [longPressState, setLongPressState] = useState<{ [key: string]: boolean }>({});
    // 作品页展示
    const [resultshow] = useAtom(resultShowAtom)
    // 图片功能所需要的参数
    const [currentProps , setCurrentProps] = useState<CurrentPropsType>({full_path:"" , api_path:"" , targetInd:0})
    // 刷新结果列表
    const [shouldFetchResults, setShouldFetchResults] = useAtom(shouldFetchResultsAtom);
	// 请求作品列表
	const getWorkList = async (params: PageParamsType) => {
		const res = await resultListServer(params.pagesize, pageParams.page);
        if (!res.data.length) {
			setHasWork(false);
            return
		}
        if(pageParams.page> 1 && !res.data.length ){
            setCurrentWorkList(true)
            changeNextPage()
            return
        }
		const processList =  res.data.map((item: WorkItemType) => {
			item.icon.icon_all = `${ALI_OSS_PATH}${item.icon.icon_all}`;
			item.result_json.forEach(
				(r: { path: string; targetInd?: number }, index: number) => {
					r.path = `${ALI_OSS_PATH}${r.path}`;
					r.targetInd = index;
				}
			);
			// @ts-ignore
			item.result_json = item.result_json.filter(
				(r: { is_del?: boolean }) => !r.is_del
			);
			let resCount = item.result_json.length;
			if (resCount === 1) {
				item.columnCount = 1;
			} else if (resCount >= 1 && resCount <= 4) {
				item.columnCount = 4;
			} else {
				item.columnCount = 9;
			}
            setLoading(false)
            return item
		});
		setWorkList((prevList)=>{
            if(!!prevList.length){
                changeNextPage()
                let data = Array.from(new Map([...prevList , ...processList].map((item) => [item.id, item])).values())
                return data
            }
            return processList
        });
	};

    // 处理长按逻辑
    const handleLongPress = (key: string , ind:number) => {
        let option ={
            full_path:key,
            api_path:`/${key.slice(key.indexOf("uploads"))}` ,
            targetInd: ind
        }
        setCurrentProps(option)
        setLongPressState((prevState) => ({
            ...prevState,
            [key]: true, // 设置该图片为长按状态
        }));
        // 动态获取每个按钮的位置信息 通过ref和measureInWindow来获取按钮的位置
        const ref = triggerButtonRefs.current[key];
        if (ref) {
            const handle = findNodeHandle(ref);
            if (handle) {
                ref.measure((x, y, width, height, pageX, pageY) => {
                    // 根据元素相对屏幕的位置 判别左弹出还是右弹出
                    (50 * vw ) >= pageX ? setSideType('left') : setSideType('right') 
                    setScrollHeight(pageY);
                    setSideViewHeight(height)
                    setSideModalShow(true); // 打开侧边栏
                });
            }
        }
    };

    // 处理长按结束（手指抬起）
    const handlePressOut = (path: string) => {
        setLongPressState((prevState) => ({
        ...prevState,
        [path]: false, // 重置为非长按状态
        }));
    };

    const gotoPreview = (id:number) => {
        router.push({
            pathname:'/preview',
            params:{
                id
            }
        })
    }

	useEffect(() => {
        console.log("pageParams" , pageParams ,userInfo.user_id  , "监听shouldFetchResults" ,shouldFetchResults);
		getWorkList(pageParams);
		// 一种解决方法 JSON.stringify(resultshow)
	}, [pageParams , resultshow,userInfo.user_id  , shouldFetchResults]);
    


	if (!hasWork) {
		return (
            <View style={[{height:100*vh - 100 *vw , paddingTop:40} , globalStyles.aiCenter]}>
                <View style={[globalStyles.rowLine , globalStyles.aiCenter]}>
                    <Text style={styles.otherText} >——当前没有没有作品，快去</Text>
                    <TouchableOpacity onPress={()=> router.navigate('/(tabs)/')}>
                        <Text style={styles.createText}>制作</Text>
                    </TouchableOpacity>
                    <Text style={styles.otherText}>吧~——</Text>
                </View>
            </View>
        );
	}
    if(loading){
        return <View style={{height:100* vh - 100 *vw}}><TransitionLoading /></View>
    }
	return (
		<View style={{ backgroundColor: "#fff" }}>
            <SideMenuWithModal 
                sideModalShow={sideModalShow}
                side={sideType}
                scrollHeight={scrollHeight}
                sideViewHeight={sideViewHeight}
                hideSideModal={()=>setSideModalShow(false)}
                openSideMoadl={()=>setSideModalShow(true)}
            >
                <WorkUse currentProps={currentProps}  hideSideModal={()=> setSideModalShow(false)} />
            </SideMenuWithModal>
			{workList.map((item: WorkItemType) => (
				<View
					key={item.id}
					style={[
						styles.workListContainer,
						globalStyles.rowLine,
						globalStyles.aiStart,
					]}
				>
					<View style={styles.icon_layout}>
						<LinearGradient
							colors={["#fff1c5", "#fffff5"]}
							style={styles.gradient}
							start={{ x: 0, y: 0 }}
							end={{ x: 0, y: 1 }}
						>
							<LazyImage
								uri={item.icon.icon_all}
								style={styles.icon}
								defaultSource={require("@/assets/common/perch.png")}
							/>
						</LinearGradient>
					</View>
					<View style={{ flex: 1 }}>
						<View>
							<Text style={styles.title}>{item.json_content.cn.title}</Text>
							<Text style={styles.desc}>{item.json_content.cn.desc}</Text>
						</View>
						<View
							style={
								item.columnCount !== 1 && [
									{ flexWrap: "wrap" },
									globalStyles.rowLine,
									globalStyles.jcFS,
									globalStyles.acSB,
								]
							}
						>
							{item.result_json.map((r: ResultItemType ) => (
                                <Pressable 
                                    key={r.path} 
                                    ref={(el) => (triggerButtonRefs.current[r.path] = el)}
                                    onPress={()=> gotoPreview(item.id)}
                                    onLongPress={() => handleLongPress(r.path , r.targetInd)}
                                    onPressOut={() => handlePressOut(r.path)} // 手指抬起时重置样式
                                >
                                    <LazyImage
                                        uri={r.path}
                                        style={[
                                            item.columnCount === 1
                                                ? styles.resImage_mode1
                                                : item.columnCount === 9
                                                ? styles.resImage_mode9
                                                : styles.resImage_mode4,
                                            longPressState[r.path] && styles.longPressedImage, // 长按时添加特殊样式
                                        ]}
                                        defaultSource={require("@/assets/common/perch.png")}
                                    />
                                </Pressable>)
                            )}
						</View>
						{/* 2.3 时间 */}
						<View
							style={[
								globalStyles.rowLine,
								globalStyles.jcSB,
								globalStyles.aiCenter,
							]}
						>
							<Text>时间:{dayjs(item.createtime).format('YYYY-MM-DD HH:mm:ss')} </Text>
							<Image
								source={require("@/assets/work/edit.png")}
								style={styles.edit}
							/>
						</View>
					</View>
				</View>
			))}
            <View style={{height:64}}>
        
                {currentWorkList && <Text style={{fontSize:10 , fontWeight:'600' , textAlign:"center"}} >没有更多作品了~</Text> }
                { nextPage && <ActivityIndicator style={{paddingVertical:12}} size="large" color="#0000ff" /> }
            </View>
		</View>
	);
}

const styles = StyleSheet.create({
	workListContainer: {
		paddingHorizontal: 4 * vw,
		marginVertical: 12,
	},
	icon_layout: {
		width: 13 * vw,
		height: 13 * vw,
		marginRight: 2 * vw,
	},
	gradient: {
		width: "100%",
		height: "100%",
		justifyContent: "center",
		alignItems: "center",
		borderColor: "#ebe7e4",
		borderWidth: 1,
		borderRadius: 8,
	},
	icon: {
		width: 8 * vw,
		height: 8 * vw,
	},
	title: {
		fontSize: 14,
		fontWeight: "600",
		color: "#000",
		marginBottom: 4,
	},
	desc: {
		fontSize: 12,
		marginBottom: 8,
	},
	resImage_mode1: {
		width: 52 * vw,
		height: 72 * vw,
		borderRadius: 12,
		marginBottom: 12,
	},
	// 一列个数为 2
	resImage_mode4: {
		width: 25 * vw,
		height: 25 * vw,
		borderRadius: 12,
		marginBottom: 12,
        marginRight: 12,
	},
	// 一列个数为 3
	resImage_mode9: {
		width: 24 * vw,
		height: 24 * vw,
		borderRadius: 12,
		marginBottom: 8,
        marginRight:8
	},
	edit: {
		width: 16,
		height: 16,
	},
    longPressedImage: {
        borderWidth: 1,
        borderColor: "#0090f1", // 长按时的边框颜色
        opacity: 0.7, // 长按时的透明度变化
    },
    otherText:{
        fontSize:13,
        fontWeight:"500",
        color:"#000"
    },
    createText:{
        fontSize:13,
        fontWeight:"600",
        color:"#007acc",
        marginHorizontal:2
    }
});
